package com.moyu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.security.exception.ServiceException;
import com.moyu.user.domain.dept.Dept;
import com.moyu.user.mapper.DeptMapper;
import com.moyu.user.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 赵彦博
 * @Date 2024/11/19 17:39
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public Dept createDept(Dept dept) {
        if (queryByDeptName(dept.getName()) != null) {
            throw new ServiceException(ResultCode.AILED_DEPT_EXISTS);
        }
        deptMapper.insert(dept);
        return dept;
    }

    @Override
    public Dept queryByDeptName(String name) {
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        Dept dept = deptMapper.selectOne(queryWrapper
                .select(Dept::getId, Dept::getName, Dept::getPrincipal, Dept::getPhoneNumber, Dept::getCreateTime, Dept::getUpdateTime)
                .eq(Dept::getName, name));
        return dept;
    }

    @Override
    public Dept queryById(Long id) {
        return deptMapper.selectById(id);
    }

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    public Dept update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
        return queryById(dept.getId());
    }

    @Override
    public boolean delete(Long id) {
        return deptMapper.delete(id) > 0;
    }
}
